/**
 * Created by Anard on 2017/4/17.
 */
var md5 = require('md5');
var publicDao = require('./publicDao.js');
var userIdDao = module.exports;
var tableName = 'user';

userIdDao.data = {};
userIdDao.change = [];

userIdDao.init = function () {
    userIdDao.data = {};
    userIdDao.change = [];

    return this;
};

userIdDao.set = function (key, value) {
    userIdDao.data[key] = value;
    userIdDao.change.push(key);

    return this;
};

userIdDao.account = function (account, cb) {
    publicDao.init().table(tableName).wheres('account', 'LIKE', account).get(function (err, res) {
        if (err !== null) {
            cb({code: err.number, msg: err.message}, null);
        } else if (res.length == 0) {
            cb(null, null);
        } else {
            userIdDao.data = res[0];
            cb(null, {res: res[0]});
        }
    });
};

userIdDao.checkPass = function (password) {
    if (userIdDao.data.password != md5(password)) {
        return false;
    }
    return true;
}

userIdDao.one = function (id, cb) {
    publicDao.init().table(tableName).wheres('id', '=', id).get(function (err, res) {
        if (err !== null) {
            cb({code: err.number, msg: err.message}, null);
        } else if (res.length == 0) {
            cb(null, null);
        } else {
            userIdDao.data = res[0];
            cb(null, {res: res[0]});
        }
    });
};

userIdDao.save = function (cb) {
    console.error('data:' + JSON.stringify(userIdDao.data));
    console.error('change:' + JSON.stringify(userIdDao.change));
    publicDao.init().table(tableName);
    if (!userIdDao.data.id) {
        for (var key in userIdDao.data) {
            publicDao.values(key, userIdDao.data[key]);
        }
        publicDao.insert(function (err, res) {
            console.error(err);
            if (err !== null) {
                cb({code: err.number, msg: err.message}, null);
            } else {
                cb(null, {res: res});
            }
        });
    } else {
        for (var i in userIdDao.change) {
            var key = userIdDao.change[i];
            console.error(key + ':' + userIdDao.data[key]);
            publicDao.values(key, userIdDao.data[key]);
        }
        publicDao.wheres('id', '=', userIdDao.data.id);
        publicDao.update(function (err, res) {
            if (err !== null) {
                cb({code: err.number, msg: err.message}, null);
            } else {
                cb(null, {res: res});
            }
        });
    }
};